import loginApi from "@/api/login"

const state = {
    token: localStorage.getItem('satoken-user') || '',//用户刷新游览器，vuex里面的值会清空
    userInfo: JSON.parse(localStorage.getItem('userInfo') || null) || {}
}
const mutations = {
    SET_TOKEN: (state,token) => {
        state.token = token
        localStorage.setItem('satoken-user',token)
    },
    CLEAR_TOKEN: (state) => {
        state.token = ''
        localStorage.removeItem('satoken-user')
    },
    SET_USER_INFO: (state,userInfo) => {
        state.userInfo = userInfo
        localStorage.setItem('userInfo',JSON.stringify(userInfo))
    },
    CLEAR_USER_INFO: (state) => {
        state.userInfo = ''
        localStorage.removeItem('userInfo')
    }
}
const actions = {
    login({commit},loginForm){
        return new Promise(((resolve, reject) => {
            loginApi.login(loginForm).then(response => {
                commit('SET_TOKEN',response.data.token)
                commit('SET_USER_INFO',response.data.userInfo)
                resolve()
            }).catch(error => {
                reject(error)
            })
        }))
    },
    logout({commit}){
        commit('CLEAR_TOKEN')
        commit('CLEAR_USER_INFO')
    }
}


export default {
    namespace: true,
    state,
    mutations,
    actions
}
